import React, {Component} from 'react';
import PubSub from 'pubsub-js'
import './index.scss'

export default class Item extends Component {

    state = {mouse: false}

    handleMouse = (flag) => {
        return () => {
            this.setState({mouse: flag})
        }
    }
    handleCheck = (id) => {
        return (event) => {
            PubSub.publish('updateTodo', {'id': id, "done": event.target.checked})
        }
    }

    handleDelete = (id) => {
        if (window.confirm('确定删除吗？')) {
            PubSub.publish('deleteTodo', id)
        }
    }


    render() {
        const {id, name, done} = this.props
        const {mouse} = this.state
        return (
            <li style={{
                backgroundColor: mouse ? '#ddd' : 'white'
            }} onMouseEnter={this.handleMouse(true)} onMouseLeave={this.handleMouse(false)}>
                <label>
                    <input type='checkbox' checked={done} onChange={this.handleCheck(id)}/>
                    <span>{name}</span>
                </label>
                <button onClick={() => this.handleDelete(id)} className='but btn-danger'
                        style={{display: mouse ? 'block' : 'none'}}>删除
                </button>
            </li>
        );
    }
}
